<?php
/**
 * Created by lihuan.
 * User: lihuan
 * Date: 2018/3/29 0029
 * Time: 下午 2:43
 */
namespace app\wxmsg\controller;

use app\common\controller\UrlTransEncrypt;
use think\Controller;

class Wxtool extends Controller {
    
    public static function is_weixin() {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        } return false;
    }
    
    public static function addEncrypt($postArr){
        $res = UrlTransEncrypt::url_value_encode(config("encrypt_key"));
        $postArr["a"]=$res["a"];
        $postArr["b"]=$res["b"];
        return $postArr;
    }
    
    //获得微信全局token
    public static function getAccessToken(){
        $post = Wxtool::addEncrypt([]);
        $json = httpPost("http://wx.yigo.fun/index/api/getWxtoken",$post);
        $res = json_decode($json, true);
        return $res;
    }

    //获取微信wx_openid
	public static function getwx_openid(){

	    $wx_openid = session("wx_openid");
		/****本地测试--start****/
//         if(get_ip()=="127.0.0.1"){
// 			return config("test_wx_openid");
// 		}
		/****本地测试--end****/

	    if (empty($wx_openid)) {
	        
	        if (!is_weixin()){
	            return null;
	        }

	        //截取客户端url的wx_openidTicket值。
	        $wx_openidTicket = isset($_GET["wx_openidTicket"])?$_GET["wx_openidTicket"]:"";

	        //从中间服务器获取wx_openid
	        $res = httpPost("http://wx.yigo.fun/index/api/getwx_openid", Wxtool::addEncrypt([
	            "wx_openidTicket"=>$wx_openidTicket
	        ]));
	        
	        $res = json_decode($res, true);
	        
	        if ($res['status'] == 1) {
	            $wx_openid = $res["data"]["wx_openid"];
	            session('wx_openid',$wx_openid);
	        } elseif ($res["status"] == - 1) {
	            
	            $appid = $res["data"]["appid"];
	            $redirect_uri = $res["data"]["redirect_uri"];
	            $wx_openidTicket = $res["data"]["wx_openidTicket"];
	            
	            //组装客户端的当前完整请求url。
	            $clientUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"];
	            //在url中加入wx_openidTicket参数。
	            if (strpos($clientUrl, "?")) {
	                $state = $clientUrl . "&wx_openidTicket=" . $wx_openidTicket;
	            } else {
	                $state = $clientUrl . "?wx_openidTicket=" . $wx_openidTicket;
	            }
	            //url编码，转换给state变量。
	            $state = urlencode($state);
	            
	            //组装重定向URL。
	            $wxUri = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=$state#wechat_redirect";
	            
	            //向客户端发起微信请求wx_openid的重定向。
	            header("Location:$wxUri");
	            exit();
	        }
	    }
	    
	    return $wx_openid;

	}


	//获取用户信息（昵称、头像、性别等）
	public static function getUserInfo($wx_openid){
    
	    $json = httpPost("http://wx.yigo.fun/index/api/getUserInfo", Wxtool::addEncrypt([
	        "wx_openid"=>$wx_openid
	    ]));
	    
	    $res = json_decode($json, true);
	    if ($res["status"]==1){
	        return $res["data"];
	    }
	   
	    show("+++++++++");
	    show($res);die;
	}
	
	//获取微信签名（用于分享）
	public static function getSignPackage() {

	    //当前用户请求的网址
	    $clientUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"];
	    
	    $res = httpPost("http://wx.yigo.fun/index/api/getSignPackage",Wxtool::addEncrypt([
	        "url"=>$clientUrl
	    ]));
	    $res = json_decode($res,true);
	    if ($res["status"]==1){
	        $signPackage = $res["data"];
	        return $signPackage;
	    }
	    show($res["msg"]);die;
	}
	

	//微信预支付功能。获取参数以后根据微信公众号js支付文档开发。
	public static function getPrePayParameter($wx_openid,$orderNo,$amount,$body,$notifyUrl){
	    $json = httpPost("http://wx.yigo.fun/index/api/getPrePayParameter", Wxtool::addEncrypt([
	        "wx_openid"=>$wx_openid,
	        "orderNo"=>$orderNo,
	        "amount"=>$amount,
	        "body"=>$body,
	        "notifyUrl"=>$notifyUrl
	    ]));
	    $res = json_decode($json, true);
	    return $res;
	}
	
	//微信预支付功能。获取参数以后根据微信公众号js支付文档开发。
	public static function getPreH5PayParameter($orderNo,$amount,$body,$notifyUrl){
	    $json = httpPost("http://wx.yigo.fun/index/api/getPreH5PayParameter", Wxtool::addEncrypt([
	        "orderNo"=>$orderNo,
	        "amount"=>$amount,
	        "body"=>$body,
	        "notifyUrl"=>$notifyUrl
	    ]));
	    echo $json;
	    $res = json_decode($json, true);
	    return $res;
	}
	
	public static function sendPacket($wx_openid,$orderNo,$amount,$act_name,$wishing,$remark){
	        
	    $json = httpPost("http://wx.yigo.fun/index/api/sendPacket", Wxtool::addEncrypt([
	        "wx_openid"=>$wx_openid, //必须
	        "orderNo"=>$orderNo, //订单号。必须
	        "amount"=>$amount, //金额。必须
	        "act_name"=>$act_name,//活动名称。必须
	        "wishing"=>$wishing,//祝福语。可选
	        "remark"=>$remark //备注。可选
	    ]));

	    $res = json_decode($json, true);
	    
	  return $res;
	}
	

	private static function httpGet($url) {
		$curl = curl_init();
		
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		// 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
		// 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);		
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($curl, CURLOPT_URL, $url);
		
		$res = curl_exec($curl);
		curl_close($curl);
		
		return $res;
	}

	/**
	 * 企业付款 提现微信支付零钱的方法
	 * @param $wx_openid 提现用户的wx_openid
	 * @param $orderNo 订单编号 可以不传，则系统默认产生订单编号
	 * @param $amount 提现金额 (单位未分)
	 * @param $desc 提现 备注
	 * @return mixed
	 */

	public static function pay($wx_openid,$amount,$desc,$orderNo=''){
		$url="http://wx.yigo.fun/index/api/pay";
		$json = httpPost($url, Wxtool::addEncrypt([
			"wx_openid"=>$wx_openid, //必须
			"orderNo"=>$orderNo, //订单号。必须
			"amount"=>$amount, //金额。必须
			"desc"=>$desc //备注。可选
		]));
         $json=Wxtool::xmlToArray($json);
		$data=[];
		if($json['result_code']=="SUCCESS"){
			$data['status']=1;
		}else{
			$data['status']=-1;
		}
		 $data['data']=$json;
		return $data;
	}
	//将XML转为array
	static function  xmlToArray($xml)
	{
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		return $values;
	}
}

